const liner = {};

const countdownLine = function(line, now) {
	const { typeTiming, stint: { timeBase, interval, render } } = line;
	let { timeNext, text } = line;

	if(!timeNext || timeNext.isSameOrBefore(now, 's')) {
		if(typeTiming == 1) {
			const diff = Math.abs(timeBase.diff(now, 's'));
			const tickNext = Math.floor(diff / interval) + 1;

			line.text = text = render(now.format());
			line.timeNext = timeNext = timeBase.clone().add(tickNext * interval, 's');
		}
	}

	return [text, tiffText(timeNext, now)];
};

let intervalLog;

const TimeHub = {
	add: (stint) => {
		const { typeTiming, id, render } = stint;

		liner[id] = { typeTiming, stint, text: render(), timeNext: null };

		if(liner[id]) { TimeHub.log(); }
	},
	del: (id) => {
		clearInterval(liner[id].stint.timer);

		delete liner[id];
	},

	log: (now = M()) => LU(
		Object.values(liner)
			.map(line => countdownLine(line, now))
			.map(([text, cd]) => `  ● 距离下次更新: ${cd}\n    ${text}`)
			.join('\n')
	),

	go: () => intervalLog = setInterval(TimeHub.log, 1000),
	stop: () => clearInterval(intervalLog)
};

module.exports = TimeHub;